package admin_rule_service

import (
	admin_rule_dao "oc_saas/internal/app/api/admin/rule/dao"
	admin_rule_types "oc_saas/internal/app/api/admin/rule/types"
	"oc_saas/internal/glo"
	"oc_saas/internal/model/share"
	oc_types "oc_saas/internal/types"
	"oc_saas/internal/types/api"
)

type Rule struct {
	api.Service
}

func (s *Rule) AddRule(data *admin_rule_types.Rule) {
	rule := admin_rule_dao.OperaRuleStructWhenAddRule(glo.OC_DB, data)
	if res := s.Orm.Where("perms = ?", data.Perms).FirstOrCreate(&rule); res.Error != nil {
		panic(&oc_types.CustomError{Msg: oc_types.SERVER_ERROR, Error: res.Error.Error()})
	} else if res.RowsAffected == 0 {
		panic(&oc_types.CustomError{Msg: oc_types.RULE_EXIST, Error: res.Error.Error()})
	}
}

// 获取规则树
func (s *Rule) GetRuleList(rule_type string, list *[]*share.Rule) {
	var ruleList []*admin_rule_types.RuleBody
	err := s.Orm.
		Model(&share.RoleRule{}).
		Select(`
			r.name,r.perms,r.type,r.id,r.p_id,r.sort,
			o.path,o.component,o.icon,o.title,o.is_link,o.is_hide,o.is_full,o.is_affix,o.is_keep_alive,o.redirect,o.is_home,
			a.type as api_type ,a.path as api_path
		`).
		Joins(`LEFT JOIN oc_rule as r on r.id = oc_role_rule.rule_id`).
		Joins(`LEFT JOIN oc_route as o on o.rule_id = r.id`).
		Joins(`LEFT JOIN oc_api as a on a.rule_id = r.id`).
		Scopes(admin_rule_dao.RuleTreeSearchDao(rule_type, glo.OC_DB)).
		Order("r.sort desc").
		Find(&ruleList).Error
	if err != nil {
		panic(&oc_types.CustomError{Msg: err.Error(), Error: err.Error()})
	}
	*list = admin_rule_dao.TransRuleTreeDao(ruleList)
}
